//
//  MBLivePlayerController.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/3/14.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBLivePlayerController.h"
#import "MBLiveMainTopCommonView.h"
#import <ViewDeck/ViewDeck.h>
#import "MBLiveInfoModel.h"
#import "MBLivePlayerBottomCommonView.h"
#import "MBShareManager.h"
#import "MBShareCommonModel.h"
#import "MBSystemFriendController.h"
#import "MBLiveMessageTableView.h"
#import "MBLiveGiftListModel.h"
#import "MBPresentGiftPopView.h"
#import "MBLiveGiftAnimationView.h"
#import "MBAccoutModel.h"
#import "MBRechargeController.h"
#import "MBKeyBoardInputField.h"
#import "MBLiveRedpacketInfoModel.h"
#import "MBLiveRedPacketView.h"
#import "MBLiveOpenRedPacketModel.h"
#import "MBLiveOpenRedPacketResultView.h"
#import "LiveGiftShowCustom.h"
#import "MBLiveViewerModel.h"
#import "MBUserDetailController.h"
#import "ThumbView.h"

@interface MBLivePlayerController ()<TXLivePlayListener,TIMMessageListener,LiveGiftShowCustomDelegate>
@property (nonatomic, strong) MBLiveMainTopCommonView *topCommonView;
@property (nonatomic, strong) MBLiveInfoModel *liveInfoModel;
@property (nonatomic, strong) NSTimer       *timer;
@property (nonatomic, strong) MBLivePlayerBottomCommonView *bottomCommonView;
@property (nonatomic, strong) MBPresentGiftPopView *presentGiftPopView;
@property (nonatomic, strong) MBLiveGiftAnimationView *giftAnimationView;
@property (nonatomic, strong) MBAccoutModel *accountModel;
@property (nonatomic, strong) MBKeyBoardInputField *inputField;
@property (nonatomic, strong) UIButton *redpacketButton;
@property (nonatomic, strong) MBLiveRedPacketView *willOpenRedPacketView;
@property (nonatomic, strong) MBLiveOpenRedPacketResultView *redPacketResultView;

@property (nonatomic, strong) MBLiveRedpacketInfoModel *redPacketInfoModel;
@property (nonatomic, strong) MBLiveOpenRedPacketModel *openRedPacketModel;
@property (nonatomic ,weak) LiveGiftShowCustom * customGiftShow;


@end

static NSInteger const LivePlayerTimerInterval = 5.0;

@implementation MBLivePlayerController
{
    CGRect      _videoWidgetFrame; //改变videoWidget的frame时候记得对其重新进行赋值
    BOOL        _recordStart;
    float       _recordProgress;
    TXLivePlayer *      _txLivePlayer;
    TXLivePlayConfig*   _config;

    BOOL        _videoPause;
    long long   _trackingTouchTS;
    UIView *    mVideoContainer;
    BOOL        _appIsInterrupt;
    BOOL                _play_switch;
    TX_Enum_PlayType _playType;
    NSString    *_playUrl;
    MBLiveMessageTableView *_msgListView; /*消息列表展示*/
}
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self createCustomNav];
    [self startRtmp];
    [self getLiveInfo];
    [self getLiveViewer];
    NSTimer *timer = [NSTimer timerWithTimeInterval:LivePlayerTimerInterval target:self selector:@selector(timerRepeat) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
    [self quitGroup];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//    [self enterGroup];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [IQKeyboardManager sharedManager].enable = NO;
//    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [IQKeyboardManager sharedManager].enable = YES;
//    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;

//    [self quitGroup];
}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.timer invalidate];
    self.timer = nil;
    [self quitGroup];
}
/*每5s 轮询获取观众*/
-(void)timerRepeat {
    [self getLiveInfo];
    [self getLiveViewer];
    [self getRedpacketInfo];
}

#pragma mark - 群聊相关
/**加入群聊*/
-(void)enterGroup {
    MBLog(@"+++++%@",self.streamID);
    [[TIMGroupManager sharedInstance] joinGroup:self.streamID msg:@"iOS" succ:^(){
        NSLog(@"Join Succ");
        [[TIMManager sharedInstance] addMessageListener:self];
        [self joinGroupSuccess];
    }fail:^(int code, NSString * err) {
        NSLog(@"code=%d, err=%@", code, err);
    }];
}
/*退出群聊*/
-(void)quitGroup {
    [[TIMGroupManager sharedInstance] quitGroup:self.streamID succ:^{
        [self enterGroup];
    } fail:^(int code, NSString *msg) {
        [self enterGroup];
    }];
}

/**发送群聊消息 */
-(void)sendMessage:(id)message {
    TIMConversation * grp_conversation = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:[NSString stringWithFormat:@"%@",self.streamID]];
    TIMMessage * msg = [[TIMMessage alloc] init];

    if ([message isKindOfClass:[NSString class]]) {/*文本消息*/
        TIMTextElem * text_elem = [[TIMTextElem alloc] init];
        [text_elem setText:message];
        [msg addElem:text_elem];
    }else { /*礼物消息*/
        TIMCustomElem *custom_elem = [[TIMCustomElem alloc]init];
        [custom_elem setData:message];
        [msg addElem:custom_elem];
    }
    [grp_conversation sendMessage:msg succ:^(){
        NSLog(@"SendMsg Succ");
    }fail:^(int code, NSString * err) {
        NSLog(@"SendMsg Failed:%d->%@", code, err);
    }];
}
/*加入直播间成功 发送一条 弹幕消息*/
-(void)joinGroupSuccess {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"3" forKey:@"type"];
    [dict setObject:filter([MBUserModel sharedMBUserModel].userInfo.nickname) forKey:@"name"];
    [dict setObject:@": 进入了直播间" forKey:@"content"];
    
    
    NSString *message = [dict mj_JSONString];
    
//    NSData* data=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    [self sendMessage:message];
}

-(void)onNewMessage:(NSArray *)msgs {
    MB_WeakSelf(self);
    for (TIMMessage *msg in msgs) {
        int elemCount = [msg elemCount];
        for (int i = 0; i < elemCount; i++) {
            TIMElem *elem = [msg getElem:i];
            if ([elem isKindOfClass:[TIMTextElem class]]) {
                TIMTextElem *textElem = (TIMTextElem *)elem;
                NSString *text = textElem.text;
                MBLog(@"群聊收到文本%@",text);
//                LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
//                msgMode.type = LiveRoomMsgModeTypeOther;
//                msgMode.time = [[NSDate date] timeIntervalSince1970];
//                //                msgMode.userName = userName;
//                msgMode.userMsg = text;
//                [_msgListView appendMsg:msgMode];
                NSDictionary* dict= (NSDictionary *)[text mj_JSONObject];
                if([dict.allKeys containsObject:@"type"]){
                    if ([dict[@"type"] isEqualToString:@"1"]) {/*礼物特效*/
                        NSString *userName = dict[@"name"];
                        NSInteger count = [dict[@"count"] integerValue];
                        NSString *giftPicture = dict[@"giftPicture"];
                        NSString *giftName = dict[@"giftName"];
                        NSString *head = dict[@"head"];
                        NSString *giftID = dict[@"id"];
                        [self showGiftBarrageViewWithGiftCount:count giftName:giftName giftURL:giftPicture userName:userName head:head giftID:giftID];
                        
                        if ([dict[@"giftUrl"] isNotBlank]) {
                            NSString *giftURL = dict[@"giftUrl"];
                            CGFloat giftTime = [dict[@"giftTime"] doubleValue];
                            self.giftAnimationView.hidden = NO;
                            [self.giftAnimationView.giftImageView yy_setImageWithURL:[NSURL URLWithString:giftURL] placeholder:nil options:YYWebImageOptionShowNetworkActivity completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(giftTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    weakself.giftAnimationView.hidden = YES;
                                });
                            }];
                        }
                    }else if ([dict[@"type"] isEqualToString:@"2"]){/*红包*/
                        
                        
                    }else if ([dict[@"type"] isEqualToString:@"3"]){/*新用户进直播间*/
                        NSString *userName = dict[@"name"];
                        NSString *content = dict[@"content"];
                        MBLog(@"++++新用户%@ 进入直播间",userName);
                        LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
                        msgMode.type = LiveRoomMsgModeTypeOther;
                        msgMode.time = [[NSDate date] timeIntervalSince1970];
                        msgMode.userMsg = [NSString stringWithFormat:@"%@",content];
                        msgMode.userName = userName;

                        [_msgListView appendMsg:msgMode];
                    }else if ([dict[@"type"] isEqualToString:@"4"]){ /*发送弹幕消息*/
                        NSString *content = dict[@"content"];
                        NSString *userName = dict[@"name"];

                        if ([content isNotBlank]) {
                            LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
                            msgMode.type = LiveRoomMsgModeTypeOther;
                            msgMode.time = [[NSDate date] timeIntervalSince1970];
                            msgMode.userMsg = [NSString stringWithFormat:@"%@",content];
                            msgMode.userName = userName;

                            [_msgListView appendMsg:msgMode];
                        }
                    }else if ([dict[@"type"] isEqualToString:@"5"]){ /*主播退出直播间*/
                        MBLog(@"主播退出直播间");
                        [MBProgressHUD showMessage:@"主播退出了直播间"];
//                        [self quitLiveRoom];
                        MBBaseTabbarController *tabVC = (MBBaseTabbarController *)weakself.viewDeckController.centerViewController;
                        [weakself.navigationController popToRootViewControllerAnimated:NO];
                        [tabVC updateCurrentIndex:0];
                    }else if ([dict[@"type"] isEqualToString:@"6"]){ /*主播踢人，观众退出直播间*/
                        [MBProgressHUD showMessage:@"您已被主播踢出房间"];
                        [weakself quitLiveRoom];
                    }else if ([dict[@"type"] isEqualToString:@"7"]){/*主播拉黑观众，观众退出直播间*/
                        [MBProgressHUD showMessage:@"您已被主播拉黑"];
                        [weakself quitLiveRoom];
                    }
                }
            }else if ([elem isKindOfClass:[TIMCustomElem class]]){
                TIMCustomElem *customElem=(TIMCustomElem*)elem;
                NSData* data=customElem.data;
                NSDictionary* dict= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                if([dict.allKeys containsObject:@"type"]){
                    if ([dict[@"type"] isEqualToString:@"1"]) {/*礼物特效*/
                        if ([dict[@"giftUrl"] isNotBlank]) {
                            NSString *giftURL = dict[@"giftUrl"];
                            CGFloat giftTime = [dict[@"giftTime"] doubleValue];
                            self.giftAnimationView.hidden = NO;
                            [self.giftAnimationView.giftImageView yy_setImageWithURL:[NSURL URLWithString:giftURL] placeholder:nil options:YYWebImageOptionShowNetworkActivity completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(giftTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    weakself.giftAnimationView.hidden = YES;
                                });
                            }];
                        }
                    }else if ([dict[@"type"] isEqualToString:@"2"]){/*红包*/
                        
                        
                    }else if ([dict[@"type"] isEqualToString:@"3"]){/*新用户进直播间*/
                        NSString *userName = dict[@"name"];
                        MBLog(@"++++新用户%@ 进入直播间",userName);
                        LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
                        msgMode.type = LiveRoomMsgModeTypeOther;
                        msgMode.time = [[NSDate date] timeIntervalSince1970];
                        msgMode.userMsg = [NSString stringWithFormat:@"%@%@",userName,@"来到直播间"];
                        [_msgListView appendMsg:msgMode];
                    }else if ([dict[@"type"] isEqualToString:@"4"]){ /*发送弹幕消息*/
                        NSString *content = dict[@"content"];
                        if ([content isNotBlank]) {
                            LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
                            msgMode.type = LiveRoomMsgModeTypeOther;
                            msgMode.time = [[NSDate date] timeIntervalSince1970];
                            msgMode.userMsg = content;
                            [_msgListView appendMsg:msgMode];
                        }
                    }
                }
            }
        }
    }
}

#pragma mark - 消息列表
- (void)appendSystemMsg:(NSString *)msg {
    LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
    msgMode.type = LiveRoomMsgModeTypeSystem;
    msgMode.userMsg = msg;
    [_msgListView appendMsg:msgMode];
}


/*获取直播详情*/
-(void)getLiveInfo {
    NSDictionary *param = @{
                            @"liveId":self.liveID,
                            @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId)
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_getLiveInfo setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        weakself.liveInfoModel = [MBLiveInfoModel mj_objectWithKeyValues:AJson];
        weakself.topCommonView.liveInfoModel = weakself.liveInfoModel;
    } failure:^(id  _Nonnull AJson) {
        
    }];
}
/*获取观众*/
-(void)getLiveViewer {
    NSDictionary *param = @{
                            @"liveId":self.liveID,
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_getLiveViewer setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        NSMutableArray *liveViewerDataArray = [MBLiveViewerModel mj_objectArrayWithKeyValuesArray:AJson];
        weakself.topCommonView.audienceDataArray = liveViewerDataArray;
        
    } failure:^(id  _Nonnull AJson) {
        
    }];
}
/**
 获取账户余额
 */
-(void)sendAccountBalanceRequest:(void(^)(MBAccoutModel *))success {
    [MBHttpRequset requestWithUrl:kTradeid_userCenter_getAccountData setParams:@{@"userId":[MBUserModel sharedMBUserModel].userInfo.userId} isShowProgressView:NO success:^(id  _Nonnull AJson) {
        self.accountModel = [[MBAccoutModel alloc]initWithDict:AJson];
        success(self.accountModel);
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

/**获取礼物效果图*/
-(void)sendGiftPictureListRequest:(void(^)(NSMutableArray *))success {
    NSDictionary *param = @{};
    [MBHttpRequset requestWithUrl:kLive_live_giftPictureList setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBLiveGiftListModel *listModel = [MBLiveGiftListModel mj_objectWithKeyValues:AJson];
        NSMutableArray *tmpArray = [NSMutableArray array];
        for (MBLiveGiftModel *model in listModel.gifts) {
            if ([model.shelfState isEqualToString:@"1"]) {
                [tmpArray addObject:model];
            }
        }
        success(tmpArray);
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

/**送礼物*/
-(void)sendLiverGift:(MBLiveGiftModel *)giftModel WithCount:(NSString *)count{
    NSDictionary *param = @{
                            @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId),
                            @"liveId":self.liveID,
                            @"giftId":giftModel.ID,
                            @"giftCount":count,
                            @"fishCoin":giftModel.giftPrice
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_sendGift setParams:param isShowProgressView:YES success:^(id  _Nonnull AJson) {
        if (giftModel.giftUrl) {
            weakself.giftAnimationView.hidden = NO;
            [weakself.giftAnimationView.giftImageView yy_setImageWithURL:[NSURL URLWithString:giftModel.giftUrl] placeholder:nil options:YYWebImageOptionShowNetworkActivity completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    weakself.giftAnimationView.hidden = YES;
                });
            }];
        }
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:@"1" forKey:@"type"];
        [dict setObject:giftModel.ID forKey:@"id"];
        [dict setObject:giftModel.giftUrl forKey:@"giftUrl"];
        [dict setObject:@(giftModel.time) forKey:@"giftTime"];
        [dict setObject:filter([MBUserModel sharedMBUserModel].userInfo.nickname) forKey:@"name"];
        [dict setObject:count forKey:@"count"];
        [dict setObject:giftModel.giftInfo forKey:@"giftPicture"];
        [dict setObject:filter([MBUserModel sharedMBUserModel].userInfo.headUrl) forKey:@"head"];
        [dict setObject:giftModel.giftname forKey:@"giftName"];
        
//        NSData* data=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        NSString *data = [dict mj_JSONString];
        [weakself sendMessage:data];

    } failure:^(id  _Nonnull AJson) {
        
    }];
}

/*获取红包信息*/
-(void)getRedpacketInfo {
    NSDictionary *param = @{
                            @"liveId":self.liveID,
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_livePlay_haveRedpacket setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBLiveRedpacketInfoModel *model = [MBLiveRedpacketInfoModel mj_objectWithKeyValues:AJson];
        weakself.redPacketInfoModel = model;
        if ([model.ifRedPacket isEqualToString:@"1"]) {
            weakself.redpacketButton.hidden = NO;
        }else {
            weakself.redpacketButton.hidden = YES;
        }
    } failure:^(id  _Nonnull AJson) {
        
    }];
}
/*抢红包*/
-(void)sendOpenRedPacketRequest {
    
    NSDictionary *param = @{
                            @"liveId":self.liveID,
                            @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId),
                            @"batchNum":self.redPacketInfoModel.batchNum ? self.redPacketInfoModel.batchNum : @"",
                            };
    MB_WeakSelf(self);
    [MBHttpRequset mb_requestWithUrl:kLive_livePlay_openRedpacket setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        NSDictionary *result = (NSDictionary *)AJson;
        if ([result[@"code"] isEqualToString:@"0000"]) {
            weakself.openRedPacketModel = [MBLiveOpenRedPacketModel mj_objectWithKeyValues:AJson[@"result"]];
            [weakself showOpenRedPacketResultView];
        }else if([result[@"code"] isEqualToString:@"2000"]){
            NSString *message = result[@"message"];
            [MBProgressHUD showMessage:message];
        }
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

-(void)jumpToUserCenterVC:(NSString *)userID {
    MBUserDetailController *vc = [[MBUserDetailController alloc]init];
    vc.userId = userID;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)createUI {
    for (UIView *view in self.view.subviews) {
        [view removeFromSuperview];
    }
    _play_switch = NO;
    _videoWidgetFrame = [UIScreen mainScreen].bounds;
    CGRect VideoFrame = [UIScreen mainScreen].bounds;
    mVideoContainer = [[UIView alloc] initWithFrame:CGRectMake(VideoFrame.size.width, 0, VideoFrame.size.width, VideoFrame.size.height)];
    [self.view insertSubview:mVideoContainer atIndex:0];
//    mVideoContainer.center = self.view.center;

    _txLivePlayer = [[TXLivePlayer alloc] init];
    [_txLivePlayer setupVideoWidget:_videoWidgetFrame containView:mVideoContainer insertIndex:0];
    _videoPause = NO;
    _trackingTouchTS = 0;
    
    // 消息列表展示和输入
    _msgListView = [[MBLiveMessageTableView alloc] initWithFrame:CGRectMake(10, kScreenHeight - 300, 300, kScreenHeight/4) style:UITableViewStyleGrouped];
    _msgListView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_msgListView];
    [self.view addSubview:self.giftAnimationView];
    
    [self.view addSubview:self.topCommonView];
    [self.view addSubview:self.inputField];
    [self.view addSubview:self.redpacketButton];
    //初始化礼物弹幕视图
    [self customGiftShow];
    MB_WeakSelf(self);
    self.topCommonView.quitBlock = ^{
        [weakself quitLiveRoom];
    };
    self.topCommonView.jumpBlock = ^(NSString * _Nonnull userID) {
        [weakself jumpToUserCenterVC:userID];
    };
    [self.view addSubview:self.bottomCommonView];
    self.bottomCommonView.shareBlock = ^{
        [weakself showShareView];
    };
    self.bottomCommonView.likeBlock = ^(UIButton * _Nonnull sender) {
        [weakself likeOrUnlike:sender];
    };
    self.bottomCommonView.giftBlock = ^{
        [weakself showGiftView];
    };
    /*发送消息*/
    self.inputField.wordFieldBlock = ^(NSString * _Nonnull wordString,MBwordFieldType type) {
        weakself.inputField.mainField.text = @"";
        [weakself.inputField.mainField resignFirstResponder];
//        [weakself sendMessage:wordString];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:@"4" forKey:@"type"];
        [dict setObject:wordString forKey:@"content"];
        [dict setObject:filter([MBUserModel sharedMBUserModel].userInfo.nickname) forKey:@"name"];
//        NSData* data=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        NSString *data = [dict mj_JSONString];
        [weakself sendMessage:data];
        
        if ([wordString isNotBlank]) {
            LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
            msgMode.type = LiveRoomMsgModeTypeOneself;
            msgMode.time = [[NSDate date] timeIntervalSince1970];
            msgMode.userMsg = [NSString stringWithFormat:@"%@",wordString];
            msgMode.userName = filter([MBUserModel sharedMBUserModel].userInfo.nickname);
            
            [_msgListView appendMsg:msgMode];
        }
        
    };
    [self.redpacketButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-12);
        make.centerY.equalTo(self.view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(40, 50));
    }];
//    self.bottomCommonView.sendMessageBlock = ^(NSString * _Nonnull message) {
//        [weakself sendMessage:message];
//    };
}
-(void)createCustomNav{
    
}

/**
 分享
 */
-(void)showShareView {
    [self sendShareInfoRequest];
}

-(void)likeOrUnlike:(UIButton *)sender {
    [self sendLikeRequest];
    ThumbView* heart = [[ThumbView alloc]initWithFrame:CGRectMake(0, 0, 36, 36)];
    [self.view addSubview:heart];
    CGPoint fountainSource = CGPointMake(kScreenWidth - 90, self.view.bounds.size.height - 36/2.0 - 10);
    heart.center = fountainSource;
    [heart thumbINView:self.view];
    
    // button点击动画
    CAKeyframeAnimation *btnAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    btnAnimation.values = @[@(1.0),@(0.7),@(0.5),@(0.3),@(0.5),@(0.7),@(1.0), @(1.2), @(1.4), @(1.2), @(1.0)];
    btnAnimation.keyTimes = @[@(0.0),@(0.1),@(0.2),@(0.3),@(0.4),@(0.5),@(0.6),@(0.7),@(0.8),@(0.9),@(1.0)];
    btnAnimation.calculationMode = kCAAnimationLinear;
    btnAnimation.duration = 0.3;
    [sender.layer addAnimation:btnAnimation forKey:@"SHOW"];
}

-(void)showGiftView {
    MB_WeakSelf(self);
    self.presentGiftPopView = [MBPresentGiftPopView nibView];
    self.presentGiftPopView.autoresizingMask = NO;
    self.presentGiftPopView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
    self.presentGiftPopView.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
    [self.view addSubview:self.presentGiftPopView];
    [self sendGiftPictureListRequest:^(NSMutableArray * giftListArray) {
        weakself.presentGiftPopView.dataArray = giftListArray;
        weakself.presentGiftPopView.cancelBlock = ^{
            [weakself.presentGiftPopView removeFromSuperview];
        };
        weakself.presentGiftPopView.jumpRechargeBlock = ^{
            MBRechargeController *rechargeVC = [[MBRechargeController alloc]init];
            rechargeVC.title = @"充值鱼币";
            rechargeVC.accoutModel = self.accountModel;
            [self.navigationController pushViewController:rechargeVC animated:YES];
        };
        weakself.presentGiftPopView.commitBlock = ^(MBLiveGiftModel * giftModel, NSString* giftCount) {
            [weakself.presentGiftPopView removeFromSuperview];
            [weakself sendLiverGift:giftModel WithCount:giftCount];
        };
        weakself.presentGiftPopView.giftCountBlock = ^{
            
        };
    }];
    
    [self sendAccountBalanceRequest:^(MBAccoutModel *model) {
          weakself.presentGiftPopView.balanceString = model.accUsrInfo.fishCoins;
    }];
}

-(void)sendShareInfoRequest {
    NSDictionary *param = @{
                            @"id":filter([MBUserModel sharedMBUserModel].userInfo.userId),
                            @"type":@(5)
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_CommonShareApi setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBShareCommonModel *model = [MBShareCommonModel mj_objectWithKeyValues:AJson];
        [[MBShareManager shareMBShareManager] mb_initShareView];
        [MBShareManager shareMBShareManager].shareTitle = @"分享标题";
        [MBShareManager shareMBShareManager].shareSubTitle = @"分享副标题";
        [MBShareManager shareMBShareManager].shareURL = model.url;
        [MBShareManager shareMBShareManager].shareImage = @"chose";
        [MBShareManager shareMBShareManager].sharePlatformBlockHandler = ^(MBSharePlatformType type) {
            switch (type) {
                case MBSharePlatformTypeSystemFriend:{
                    [weakself showSystemFriend];
                }break;
            }
        };
        
    } failure:^(id  _Nonnull AJson) {
        
    }];
}
-(void)showSystemFriend {
    MBSystemFriendController *vc = [[MBSystemFriendController alloc]init];
    vc.liveID = self.liveID;
    [self.navigationController pushViewController:vc animated:YES];
}

/*退出直播间*/
-(void)quitLiveRoom {
    [self quitGroup];
    NSDictionary *param = @{
                             @"liveId":self.liveID,
                             @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId)
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_audienceClose setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBBaseTabbarController *tabVC = (MBBaseTabbarController *)weakself.viewDeckController.centerViewController;
        [weakself.navigationController popToRootViewControllerAnimated:NO];
        [tabVC updateCurrentIndex:0];
        
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

-(void)sendLikeRequest {
    NSDictionary *param = @{
                            @"liveId":self.liveID,
                            @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId),
                            @"nickname":filter([MBUserModel sharedMBUserModel].userInfo.nickname),
                              @"headUrl":filter([MBUserModel sharedMBUserModel].userInfo.headUrl),
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_livePlay_like setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        [weakself.bottomCommonView setLikeOrUnLike:YES];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

-(void)showOpenRedPacketResultView {
     [APP_delegate.window addSubview:self.redPacketResultView];
    self.redPacketResultView.moneyString = self.openRedPacketModel.money;
    MB_WeakSelf(self);
    self.redPacketResultView.cancelBlock = ^{
        [weakself.redPacketResultView removeFromSuperview];
        weakself.redPacketResultView = nil;
    };
}

-(void)showGiftBarrageViewWithGiftCount:(NSInteger)count giftName:(NSString *)giftName giftURL:(NSString *)giftURL userName:(NSString *)userName head:(NSString *)head giftID:(NSString *)giftID{
    LiveUserModel *userModel = [[LiveUserModel alloc]init];
    userModel.name = userName;
    userModel.iconUrl = head;
    LiveGiftListModel *giftModel = [[LiveGiftListModel alloc]init];
    giftModel.type = giftID;
    giftModel.name = giftName;
    giftModel.picUrl = giftURL;
    giftModel.rewardMsg = @"";
    
    LiveGiftShowModel * model = [LiveGiftShowModel giftModel:giftModel userModel:userModel];
    model.toNumber = count;
    model.interval = 0.15;
    [self.customGiftShow animatedWithGiftModel:model];
}

#pragma mark - event
-(void)showRedPacket:(UIButton *)sender {
    [APP_delegate.window addSubview:self.willOpenRedPacketView];
    MB_WeakSelf(self);
    self.willOpenRedPacketView.openBlock = ^{
        [weakself sendOpenRedPacketRequest];
        [weakself.willOpenRedPacketView removeFromSuperview];
        weakself.willOpenRedPacketView = nil;
    };
    self.willOpenRedPacketView.cancelBlock = ^{
        [weakself.willOpenRedPacketView removeFromSuperview];
        weakself.willOpenRedPacketView = nil;
    };
}

#pragma mark - NSNotification
/*键盘展开*/
- (void)keyBoardWillShow:(NSNotification *) note {
    // 获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    // 获取键盘高度
    CGRect keyBoardBounds  = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyBoardHeight = keyBoardBounds.size.height;
    // 获取键盘动画时间
    CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect begin = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGFloat currenKeyBoardHeight = [[userInfo objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size.height;
    if (begin.size.height > 0 && (begin.origin.y - keyBoardBounds.origin.y > 0)) {
        keyBoardHeight = currenKeyBoardHeight;
        MBLog(@"键盘高度%@ +++ %lf",NSStringFromCGRect(keyBoardBounds),keyBoardHeight);
        
        // 定义好动作
        void (^animation)(void) = ^void(void) {
            self.inputField.transform = CGAffineTransformMakeTranslation(0, -keyBoardHeight - 100);
            [self.inputField.mainField becomeFirstResponder];
        };
        if (animationTime > 0) {
            [UIView animateWithDuration:animationTime animations:animation];
        } else {
            animation();
        }
    }
}
/*键盘收起*/
- (void)keyBoardWillHide:(NSNotification *) note {
    // 获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    // 获取键盘动画时间
    CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        self.inputField.transform = CGAffineTransformIdentity;
    };
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
        [self.inputField.mainField resignFirstResponder];

    } else {
        animation();
    }
}

//在低系统（如7.1.2）可能收不到这个回调，请在onAppDidEnterBackGround和onAppWillEnterForeground里面处理打断逻辑
- (void) onAudioSessionEvent: (NSNotification *) notification
{
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        if (_play_switch == YES && _appIsInterrupt == NO) {
            _appIsInterrupt = YES;
        }
    }else{
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            // 收到该事件不能调用resume，因为此时可能还在后台
            /*
             if (_play_switch == YES && _appIsInterrupt == YES) {
             if ([self isVODType:_playType]) {
             if (!_videoPause) {
             [_txLivePlayer resume];
             }
             }
             _appIsInterrupt = NO;
             }
             */
        }
    }
}
- (void)onAppWillEnterForeground:(UIApplication*)app {
    if (_play_switch == YES) {
        if ([self isVODType:_playType]) {
            if (!_videoPause) {
                [_txLivePlayer resume];
            }
        }
    }
}
- (void)onAppDidEnterBackGround:(UIApplication*)app {
    if (_play_switch == YES) {
        if ([self isVODType:_playType]) {
            if (!_videoPause) {
                [_txLivePlayer pause];
            }
        }
    }
}
- (void)onAppDidBecomeActive:(UIApplication*)app {
    if (_play_switch == YES && _appIsInterrupt == YES) {
        if ([self isVODType:_playType]) {
            if (!_videoPause) {
                [_txLivePlayer resume];
            }
        }
        _appIsInterrupt = NO;
    }
}
-(void)onAppWillTerminate:(NSNotification *)notification {
    [[TIMGroupManager sharedInstance] quitGroup:self.streamID succ:^{
    } fail:^(int code, NSString *msg) {
    }];
    [self quitLiveRoom];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
//    if (_play_switch == YES) {
//        [self stopRtmp];
//    }
    [self stopRtmp];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackGround:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
}

-(BOOL)startRtmp{
    CGRect frame = CGRectMake(self.view.bounds.size.width, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    mVideoContainer.frame = frame;
//    [_loadingImageView removeFromSuperview];
    NSString* playUrl = self.rtmpString;
    if (![self checkPlayUrl:playUrl]) {
        return NO;
    }
    
    //    [self clearLog];
    
    // arvinwu add. 增加播放按钮事件的时间打印。
    unsigned long long recordTime = [[NSDate date] timeIntervalSince1970]*1000;
    int mil = recordTime%1000;
    NSDateFormatter* format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"hh:mm:ss";
    NSString* time = [format stringFromDate:[NSDate date]];
    NSString* log = [NSString stringWithFormat:@"[%@.%-3.3d] 点击播放按钮", time, mil];
    
//    _logMsg = [NSString stringWithFormat:@"liteav sdk version: %@\n%@", ver, log];
    //    [_logViewEvt setText:_logMsg];
    
    
    if(_txLivePlayer != nil)
    {
        _txLivePlayer.delegate = self;
        //        _txLivePlayer.recordDelegate = self;
        //        _txLivePlayer.videoProcessDelegate = self;
        if (self.isLivePlay) {
            [_txLivePlayer setupVideoWidget:CGRectMake(0, 0, 0, 0) containView:mVideoContainer insertIndex:0];
        }
        
        if (_config == nil){
            _config = [[TXLivePlayConfig alloc] init];
        }
        _config.cacheFolderPath = nil;
        _config.playerPixelFormatType = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
        //        _config.headers = @{@"Referer": @"qcloud.com"};
        [_txLivePlayer setConfig:_config];
        
        //设置播放器缓存策略
        //这里将播放器的策略设置为自动调整，调整的范围设定为1到4s，您也可以通过setCacheTime将播放器策略设置为采用
        //固定缓存时间。如果您什么都不调用，播放器将采用默认的策略（默认策略为自动调整，调整范围为1到4s）
        //[_txLivePlayer setCacheTime:5];
        //[_txLivePlayer setMinCacheTime:1];
        //[_txLivePlayer setMaxCacheTime:4];
        //        _txLivePlayer.isAutoPlay = NO;
        //        [_txLivePlayer setRate:1.5];
        //        [_txLivePlayer setMute:YES];
        //        NSURL *MyURL = [[NSBundle mainBundle]
        //                        URLForResource: @"goodluck" withExtension:@"mp4"];
        //        int result = [_txLivePlayer startPlay:[MyURL relativePath] type:PLAY_TYPE_LOCAL_VIDEO];
        int result = [_txLivePlayer startPlay:playUrl type:_playType];
//        [_txLivePlayer showVideoDebugLog:_log_switch];
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CGRect frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
        [UIView animateWithDuration:0.4 animations:^{
            mVideoContainer.frame = frame;
        } completion:^(BOOL finished) {
//            [self.view addSubview:_loadingImageView];
        }];
        //        });
        
        
        if( result != 0)
        {
            NSLog(@"播放器启动失败");
            return NO;
        }
        
        [_txLivePlayer setRenderRotation:HOME_ORIENTATION_DOWN];

//        [self startLoadingAnimation];
        
        _videoPause = NO;
//        [_btnPlay setImage:[UIImage imageNamed:@"suspend"] forState:UIControlStateNormal];
    }
//    [self startLoadingAnimation];
//    _startPlayTS = [[NSDate date]timeIntervalSince1970]*1000;
    
    _playUrl = playUrl;
    return YES;
}

- (void)stopRtmp{
    _playUrl = @"";
//    [self stopLoadingAnimation];
    if(_txLivePlayer != nil)
    {
        [_txLivePlayer stopPlay];
//        [_btnMute setImage:[UIImage imageNamed:@"mic"] forState:UIControlStateNormal];
//        [_btnMute setHighlighted:NO];
        [_txLivePlayer removeVideoWidget];
        _txLivePlayer.delegate = nil;
    }
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:nil];
}


-(BOOL)isVODType:(int)playType {
    if (playType == PLAY_TYPE_VOD_FLV || playType == PLAY_TYPE_VOD_HLS || playType == PLAY_TYPE_VOD_MP4 || playType == PLAY_TYPE_LOCAL_VIDEO) {
        return YES;
    }
    return NO;
}
-(BOOL)checkPlayUrl:(NSString*)playUrl {
    if (self.isLivePlay) {
        if (self.isRealtime) {
            _playType = PLAY_TYPE_LIVE_RTMP_ACC;
            if (!([playUrl containsString:@"txSecret"] || [playUrl containsString:@"txTime"])) {
//                ToastTextView *toast = [self toastTip:@"低延时拉流地址需要防盗链签名，详情参考 https://cloud.tencent.com/document/product/454/7880#RealTimePlay"];
//                toast.url = @"https://cloud.tencent.com/document/product/454/7880#RealTimePlay";
                return NO;
            }
            
        }
        else {
            if ([playUrl hasPrefix:@"rtmp:"]) {
                _playType = PLAY_TYPE_LIVE_RTMP;
            } else if (([playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"http:"]) && ([playUrl rangeOfString:@".flv"].length > 0)) {
                _playType = PLAY_TYPE_LIVE_FLV;
            } else if (([playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"http:"]) && [playUrl rangeOfString:@".m3u8"].length > 0) {
                _playType = PLAY_TYPE_VOD_HLS;
            } else{
//                [self toastTip:@"播放地址不合法，直播目前仅支持rtmp,flv播放方式!"];
                return NO;
            }
        }
    } else {
        if ([playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"http:"]) {
            if ([playUrl rangeOfString:@".flv"].length > 0) {
                _playType = PLAY_TYPE_VOD_FLV;
            } else if ([playUrl rangeOfString:@".m3u8"].length > 0){
                _playType= PLAY_TYPE_VOD_HLS;
            } else if ([playUrl rangeOfString:@".mp4"].length > 0){
                _playType= PLAY_TYPE_VOD_MP4;
            } else {
//                [self toastTip:@"播放地址不合法，点播目前仅支持flv,hls,mp4播放方式!"];
                return NO;
            }
            
        } else {
            _playType = PLAY_TYPE_LOCAL_VIDEO;
        }
    }
    
    return YES;
}
#pragma ###TXLivePlayListener

-(void) onPlayEvent:(int)EvtID withParam:(NSDictionary*)param
{
    NSDictionary* dict = param;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (EvtID == PLAY_EVT_RCV_FIRST_I_FRAME) {
            //            _publishParam = nil;
        }
        
        if (EvtID == PLAY_EVT_PLAY_BEGIN) {
//            [self stopLoadingAnimation];
//            long long playDelay = [[NSDate date]timeIntervalSince1970]*1000 - _startPlayTS;
//            AppDemoLog(@"AutoMonitor:PlayFirstRender,cost=%lld", playDelay);
        } else if (EvtID == PLAY_EVT_PLAY_PROGRESS) {
//            if (_startSeek) {
//                return;
//            }
            // 避免滑动进度条松开的瞬间可能出现滑动条瞬间跳到上一个位置
            long long curTs = [[NSDate date]timeIntervalSince1970]*1000;
            if (llabs(curTs - _trackingTouchTS) < 500) {
                return;
            }
            _trackingTouchTS = curTs;
            
            float progress = [dict[EVT_PLAY_PROGRESS] floatValue];
            float duration = [dict[EVT_PLAY_DURATION] floatValue];
            
            int intProgress = progress + 0.5;
//            _playStart.text = [NSString stringWithFormat:@"%02d:%02d", (int)(intProgress / 60), (int)(intProgress % 60)];
//            [_playProgress setValue:progress];
            
            int intDuration = duration + 0.5;
//            if (duration > 0 && _playProgress.maximumValue != duration) {
//                [_playProgress setMaximumValue:duration];
//                [_playableProgress setMaximumValue:duration];
//                _playDuration.text = [NSString stringWithFormat:@"%02d:%02d", (int)(intDuration / 60), (int)(intDuration % 60)];
//            }
//
//            [_playableProgress setValue:[dict[EVT_PLAYABLE_DURATION] floatValue]];
            return ;
        } else if (EvtID == PLAY_ERR_NET_DISCONNECT || EvtID == PLAY_EVT_PLAY_END) {
            [self stopRtmp];
            _play_switch = NO;
//            [_btnPlay setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
            [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
//            [_playProgress setValue:0];
//            _playStart.text = @"00:00";
            _videoPause = NO;
            
            if (EvtID == PLAY_ERR_NET_DISCONNECT) {
                NSString* Msg = (NSString*)[dict valueForKey:EVT_MSG];
//                [self toastTip:Msg];
            }
            
        } else if (EvtID == PLAY_EVT_PLAY_LOADING){
//            [self startLoadingAnimation];
        }
        else if (EvtID == PLAY_EVT_CONNECT_SUCC) {
            [self getLiveInfo];
            [self getLiveViewer];
            BOOL isWifi = [AFNetworkReachabilityManager sharedManager].reachableViaWiFi;
            if (!isWifi) {
                __weak __typeof(self) weakSelf = self;
                [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
                    if (_playUrl.length == 0) {
                        return;
                    }
                    if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                                       message:@"您要切换到Wifi再观看吗?"
                                                                                preferredStyle:UIAlertControllerStyleAlert];
                        [alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            [alert dismissViewControllerAnimated:YES completion:nil];
                            [weakSelf stopRtmp];
                            [weakSelf startRtmp];
                        }]];
                        [alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                            [alert dismissViewControllerAnimated:YES completion:nil];
                        }]];
                        [weakSelf presentViewController:alert animated:YES completion:nil];
                    }
                }];
            }
        }else if (EvtID == PLAY_EVT_CHANGE_ROTATION) {
            return;
        }
        //        NSLog(@"evt:%d,%@", EvtID, dict);
        long long time = [(NSNumber*)[dict valueForKey:EVT_TIME] longLongValue];
        int mil = time % 1000;
        NSDate* date = [NSDate dateWithTimeIntervalSince1970:time/1000];
        NSString* Msg = (NSString*)[dict valueForKey:EVT_MSG];
    });
}

-(void) onNetStatus:(NSDictionary*) param
{
    NSDictionary* dict = param;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        int netspeed  = [(NSNumber*)[dict valueForKey:NET_STATUS_NET_SPEED] intValue];
        int vbitrate  = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_BITRATE] intValue];
        int abitrate  = [(NSNumber*)[dict valueForKey:NET_STATUS_AUDIO_BITRATE] intValue];
        int cachesize = [(NSNumber*)[dict valueForKey:NET_STATUS_CACHE_SIZE] intValue];
        int dropsize  = [(NSNumber*)[dict valueForKey:NET_STATUS_DROP_SIZE] intValue];
        int jitter    = [(NSNumber*)[dict valueForKey:NET_STATUS_NET_JITTER] intValue];
        int fps       = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_FPS] intValue];
        int width     = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_WIDTH] intValue];
        int height    = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_HEIGHT] intValue];
        float cpu_usage = [(NSNumber*)[dict valueForKey:NET_STATUS_CPU_USAGE] floatValue];
        float cpu_app_usage = [(NSNumber*)[dict valueForKey:NET_STATUS_CPU_USAGE_D] floatValue];
        NSString *serverIP = [dict valueForKey:NET_STATUS_SERVER_IP];
        int codecCacheSize = [(NSNumber*)[dict valueForKey:NET_STATUS_CODEC_CACHE] intValue];
        int nCodecDropCnt = [(NSNumber*)[dict valueForKey:NET_STATUS_CODEC_DROP_CNT] intValue];
        int nCahcedSize = [(NSNumber*)[dict valueForKey:NET_STATUS_CACHE_SIZE] intValue]/1000;
        int nSetVideoBitrate = [(NSNumber *) [dict valueForKey:NET_STATUS_SET_VIDEO_BITRATE] intValue];
        int videoCacheSize = [(NSNumber *) [dict valueForKey:NET_STATUS_VIDEO_CACHE_SIZE] intValue];
        int vDecCacheSize = [(NSNumber *) [dict valueForKey:NET_STATUS_V_DEC_CACHE_SIZE] intValue];
        int playInterval = [(NSNumber *) [dict valueForKey:NET_STATUS_AV_PLAY_INTERVAL] intValue];
        int avRecvInterval = [(NSNumber *) [dict valueForKey:NET_STATUS_AV_RECV_INTERVAL] intValue];
        float audioPlaySpeed = [(NSNumber *) [dict valueForKey:NET_STATUS_AUDIO_PLAY_SPEED] floatValue];
        NSString * audioInfo = [dict valueForKey:NET_STATUS_AUDIO_INFO];
        int videoGop = (int)([(NSNumber *) [dict valueForKey:NET_STATUS_VIDEO_GOP] doubleValue]+0.5f);
        NSString* log = [NSString stringWithFormat:@"CPU:%.1f%%|%.1f%%\tRES:%d*%d\tSPD:%dkb/s\nJITT:%d\tFPS:%d\tGOP:%ds\tARA:%dkb/s\nQUE:%d|%d,%d,%d|%d,%d,%0.1f\tVRA:%dkb/s\nSVR:%@\tAUDIO:%@",
                         cpu_app_usage*100,
                         cpu_usage*100,
                         width,
                         height,
                         netspeed,
                         jitter,
                         fps,
                         videoGop,
                         abitrate,
                         codecCacheSize,
                         cachesize,
                         videoCacheSize,
                         vDecCacheSize,
                         avRecvInterval,
                         playInterval,
                         audioPlaySpeed,
                         vbitrate,
                         serverIP,
                         audioInfo];
//        AppDemoLogOnlyFile(@"Current status, VideoBitrate:%d, AudioBitrate:%d, FPS:%d, RES:%d*%d, netspeed:%d", vbitrate, abitrate, fps, width, height, netspeed);
    });
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
#pragma mark - getter and setter
-(MBLiveMainTopCommonView *)topCommonView {
    if (_topCommonView == nil) {
        _topCommonView = [MBLiveMainTopCommonView nibView];
        _topCommonView.autoresizingMask = NO;
        _topCommonView.backgroundColor = [UIColor clearColor];
        _topCommonView.frame = (CGRect){{0,kNavStatusHeight},{kScreenWidth,60}};
    }
    return _topCommonView;
}
-(MBLivePlayerBottomCommonView *)bottomCommonView {
    if (_bottomCommonView == nil) {
        _bottomCommonView = [MBLivePlayerBottomCommonView nibView];
        _bottomCommonView.autoresizingMask = NO;
        _bottomCommonView.backgroundColor = [UIColor clearColor];
        _bottomCommonView.frame = (CGRect){{0,kScreenHeight - kTabSafeBottomMargin - 60},{kScreenWidth,60}};
    }
    return _bottomCommonView;
}
-(MBLiveGiftAnimationView *)giftAnimationView {
    if (_giftAnimationView == nil) {
        _giftAnimationView = [[MBLiveGiftAnimationView alloc]initWithFrame:(CGRect){{0,0},{kScreenWidth,kScreenHeight}}];
        _giftAnimationView.autoresizingMask = NO;
//        _giftAnimationView.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
        _giftAnimationView.backgroundColor = [UIColor clearColor];
        _giftAnimationView.hidden = YES;
    }
    return _giftAnimationView;
}
-(MBKeyBoardInputField *)inputField {
    if (_inputField == nil) {
        _inputField = [MBKeyBoardInputField nibView];
        _inputField.frame = CGRectMake(0, kScreenHeight + 40, kScreenWidth, 40);
    }
    return _inputField;
}
-(UIButton *)redpacketButton {
    if (_redpacketButton == nil) {
        _redpacketButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_redpacketButton setImage:kImage(@"hongbao6") forState:UIControlStateNormal];
        _redpacketButton.hidden = YES;
        [_redpacketButton addTarget:self action:@selector(showRedPacket:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _redpacketButton;
}

-(MBLiveRedPacketView *)willOpenRedPacketView {
    if (_willOpenRedPacketView == nil) {
        _willOpenRedPacketView = [MBLiveRedPacketView nibView];
        _willOpenRedPacketView.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
        _willOpenRedPacketView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    }
    return _willOpenRedPacketView;
}
-(MBLiveOpenRedPacketResultView *)redPacketResultView {
    if (_redPacketResultView == nil) {
        _redPacketResultView = [MBLiveOpenRedPacketResultView nibView];
        _redPacketResultView.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
        _redPacketResultView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    }
    return _redPacketResultView;
}
/*
 礼物视图支持很多配置属性，开发者按需选择。
 */
- (LiveGiftShowCustom *)customGiftShow{
    if (!_customGiftShow) {
        _customGiftShow = [LiveGiftShowCustom addToView:self.view];
        _customGiftShow.addMode = LiveGiftAddModeAdd;
        [_customGiftShow setMaxGiftCount:3];
        [_customGiftShow setShowMode:LiveGiftShowModeFromTopToBottom];
        [_customGiftShow setAppearModel:LiveGiftAppearModeLeft];
        [_customGiftShow setHiddenModel:LiveGiftHiddenModeNone];
        [_customGiftShow enableInterfaceDebug:YES];
        _customGiftShow.delegate = self;
    }
    return _customGiftShow;
}
//-(MBPresentGiftPopView *)presentGiftPopView {
//    if (_presentGiftPopView == nil) {
//        _presentGiftPopView = [MBPresentGiftPopView nibView];
//        _presentGiftPopView.autoresizingMask = NO;
//        _presentGiftPopView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
//        _presentGiftPopView.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
//    }
//    return _presentGiftPopView;
//}
@end
